import java.util.HashMap;
import java.util.Map;

public class Solution653 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean findTarget(TreeNode root, int k) {
        Map<Integer,Integer> map=new HashMap<>();
        dfs(root,map);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getKey()*2==k){
                if (entry.getValue()>=2){
                    return true;
                }
            }else{
                if (map.containsKey(k-entry.getKey())){
                    return true;
                }
            }
        }
        return false;
    }

    private void dfs(TreeNode root, Map<Integer, Integer> map) {
        if (root==null){
            return;
        }
        map.put(root.val,map.getOrDefault(root.val,0)+1);
        dfs(root.left,map);
        dfs(root.right,map);
    }

    public static void main(String[] args) {
        System.out.println(new Solution653().findTarget(new TreeNode(5,new TreeNode(3,new TreeNode(2),new TreeNode(4)),new TreeNode(6,null,new TreeNode(7))),9));
    }
}
